<template>
	<div>
		<div class="search_form">
			<div>
				<el-select size="mini" clearable placeholder="请选择船名航次" v-model="searchform.shipvoyageId">
					<el-option
						v-for="(item, index) in shipVoyageData"
						:key="index"
						:label="item.shipvoyageName"
						:value="item.shipvoyageId"
					></el-option>
				</el-select>
				<el-button @click="searchData" class="search_btn" type="primary" icon="el-icon-search" size="mini">查询</el-button>
			</div>
			<div>
				<el-button type="primary" size="mini" @click="showDetail" v-hasPermi="['yardManagement:TYardLoadingList:insert']">
					清单
				</el-button>
			</div>
		</div>
		<BaseTable
			:data="tableData"
			:columns="columns"
			@details="handlerClickDetails"
			:tableHeight="tableHeight"
			:pagination="queryall"
			@size-change="sizeChange"
			@current-change="pageChange"
			:loading="loading"
		></BaseTable>
		<!-- 清单 -->
		<el-drawer
			title="装船清单"
			label-width="120px"
			:visible.sync="isShow"
			destroy-on-close
			direction="rtl"
			size="60%"
			:before-close="handleClose"
		>
			<el-form :model="formitem" style="padding: 10px 20px">
				<el-row>
					<el-col :span="8">
						<el-form-item label="船名航次">
							<el-input size="mini" v-model="formitem.shipvoyageName" readonly></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="货种">
							<el-input size="mini" v-model="formitem.cargoCategoryName" readonly></el-input>
						</el-form-item>
					</el-col>
					<el-col :span="8">
						<el-form-item label="客户名称">
							<el-input size="mini" v-model="formitem.customerName" readonly></el-input>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<el-collapse v-model="activeNames" style="position: relative">
				<el-collapse-item title="清单" name="1">
					<el-button-group>
						<el-button v-for="(item, index) in cabinNoList" :key="index" @click="addTab(item.cabinNo)">
							{{ item.cabinNo }}
						</el-button>
					</el-button-group>
					<div style="position: absolute; top: 17%; z-index: 9999; right: 2%">
						<el-button type="primary" size="mini" @click="showDetailData">添加</el-button>
					</div>
					<el-tabs
						style="margin-top: 10px"
						v-model="editableTabsValue"
						@tab-click="handleClick(editableTabsValue)"
						type="card"
						closable
						@tab-remove="removeTab"
					>
						<el-tab-pane v-for="(item, index) in editableTabs" :key="index" :label="item.title" :name="item.name">
							<el-table
								border
								v-tableMove
                height="400px"
								:data="item.detailTableData"
								stripe
								highlight-current-row
								style="width: 100%"
							>
								<el-table-column prop="cargoOwnerName" width="150" label="货主" show-overflow-tooltip />
								<el-table-column prop="cargoAgentName" label="货代" show-overflow-tooltip />
								<el-table-column prop="cargoName" label="货名" show-overflow-tooltip />
								<el-table-column prop="place" label="位置" width="120" show-overflow-tooltip />
								<el-table-column prop="pieceNo" label="件号" show-overflow-tooltip>
									<!-- <template slot-scope="scope">
										<span v-if="scope.row.pieceNo" @click="openPieceNoDrawer(scope.row, scope.$index)">
											{{ scope.row.pieceNo }}
										</span>
										<el-button v-else size="mini" type="text" @click="openPieceNoDrawer(scope.row, scope.$index)">
											件号
										</el-button>
									</template> -->
								</el-table-column>
								<el-table-column label="件数">
									<template slot-scope="scope">
                    <span v-if="scope.row.pieceNo != '' && scope.row.pieceNo != null">
                      {{scope.row.quantity}}
                    </span>
                    <el-input
                      v-else
											v-model="scope.row.quantity"
                      clearable
											size="mini"
											@input="scope.row.quantity = verifyfilter('number', scope.row.quantity)"
										/>
									</template>
								</el-table-column>
								<el-table-column label="重量">
									<template slot-scope="scope">
                    <span v-if="scope.row.pieceNo != '' && scope.row.pieceNo != null">
                      {{scope.row.ton}}
                    </span>
										<el-input
                      v-else
											v-model="scope.row.ton"
											size="mini"
											@input="scope.row.ton = verifyfilter('digit', scope.row.ton)"
										/>
									</template>
								</el-table-column>
								<el-table-column label="操作">
									<template slot-scope="scope">
										<el-button size="mini" type="text" @click="handlerClickDetail(item.detailTableData, scope.$index)">
											删除
										</el-button>
									</template>
								</el-table-column>
							</el-table>
						</el-tab-pane>
					</el-tabs>
				</el-collapse-item>
			</el-collapse>
			<div class="demo-drawer__footer">
				<el-button size="small" type="primary" @click="saveInventory()">保存</el-button>
			</div>
		</el-drawer>
		<!-- 件号 -->
		<el-dialog title="件号" :visible.sync="dialogVisible" width="30%">
			<el-checkbox-group v-model="checkedCities" @change="checkChange">
				<el-checkbox v-for="(item, index) in pieceNo" :label="item.pieceNo" :key="index">{{ item.pieceNo }}</el-checkbox>
			</el-checkbox-group>
			<span slot="footer" class="dialog-footer">
				<el-button @click="dialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="submitPieceNo">确 定</el-button>
			</span>
		</el-dialog>
    <!-- 选择舱口数据 -->
    <el-drawer
			title="舱口数据"
			label-width="120px"
			:visible.sync="showDetailDrawer"
			destroy-on-close
			direction="rtl"
			size="60%"
		>
      <div class="search_form">
			  <div>
			  	<el-date-picker
            style="width: 180px"
            v-model="detailForm.inOutDate"
            type="date"
            size="mini"
            value-format="yyyy-MM-dd"
            format="yyyy-MM-dd"
            clearable
            placeholder="选择出入库日期">
          </el-date-picker>
          <el-input v-model="detailForm.stackPosition" placeholder="请输入垛号" size="mini" clearable class="others"></el-input>
          <el-input v-model="detailForm.pieceNo" placeholder="请输入件号" size="mini" clearable class="others"></el-input>
			  	<el-button @click="searchDetailData" class="search_btn" type="primary" icon="el-icon-search" size="mini">查询</el-button>
			  </div>
		  </div>
      <BaseTableCheck 
        ref="showFrontEdgeForEdit"
        :loading="detailloading"
        :data="detailData"
        :columns="detailcolumns" 
        :tableHT="tableHeight" 
        :pagination="false" 
        @checkId="detailChange"></BaseTableCheck>
      <div class="demo-drawer__footer">
				<el-button size="small" type="primary" @click="saveDetailData">保存</el-button>
			</div>
    </el-drawer>
	</div>
</template>

<script>
// 装船清单
import api from "@/api/yardTally/shippingList"
import publicapi from "@/api/public/index"
import BaseTable from "@/components/BaseTable"
import BaseTableCheck from '@/components/BaseTable/baseTablecheck'
export default {
	components: { BaseTable,BaseTableCheck },
	data() {
		return {
			shipVoyageData: [], // 船名行次下拉框
			tableHeight: window.innerHeight - 200,
			searchform: {
				shipvoyageId: "",
			},
			loading: false,
			tableData: [], // 列表
			columns: [
				{
					prop: "shipvoyageName",
					label: "船名航次",
				},
				{
					prop: "shipReportStatus",
					label: "状态",
					render: (h, params) => {
						if (params.row.shipReportStatus == "1") {
							return h("el-tag", {
								props: {
									size: "mini",
								},
								domProps: {
									innerHTML: "未确认",
								},
							})
						} else if (params.row.shipReportStatus == "2") {
							return h("el-tag", {
								props: {
									size: "mini",
									type: "success",
								},
								domProps: {
									innerHTML: "已确认",
								},
							})
						}
					},
				},
				{
					prop: "companyName",
					label: "业务单元",
				},
				{
					prop: "customerName",
					label: "客户名称",
				},
				{
					prop: "tradeType",
					label: "贸别",
				},
				{
					prop: "cargoCategoryName",
					label: "货种",
				},
				{
					prop: "arrivalTimePlan",
					label: "预抵时间",
				},
			],
			deatilInfo: null, // 列表行数据
			// 页码
			queryall: {
				totalNum: 0,
				startpage: 1,
				pagesize: 15,
			},
			isShow: false,
			formitem: {
				shipvoyageName: "",
				cargoCategoryName: "",
				companyName: "",
				customerName: "",
			},
			editableTabsValue: "1",
			// 预设舱口
			cabinNoList: [
				{
					cabinNo: "1",
				},
				{
					cabinNo: "2",
				},
				{
					cabinNo: "3",
				},
				{
					cabinNo: "4",
				},
				{
					cabinNo: "5",
				},
				{
					cabinNo: "6",
				},
				{
					cabinNo: "7",
				},
				{
					cabinNo: "8",
				},
			],
			activeNames: "1",
			editableTabs: [
				// {
				//   title: '1舱口',
				//   name: '1',
				//   detailTableData: []
				// },
			],
			listTableData: [],
			detailcolumns: [
				{
					prop: "cargoOwnerName",
					label: "货主",
					width: 150,
				},
				{
					prop: "cargoAgentName",
					label: "货代",
					width: 150,
				},
				{
					prop: "cargoName",
					label: "货名",
				},
				{
					prop: "place",
					label: "位置",
				},
				{
					prop: "pieceNoPin",
					label: "件号",
				},
				{
					prop: "quantity",
					label: "件数",
					render: (h, params) => {
						return (
							<div>
								{h("el-input", {
									props: {
										value: params.row.quantity,
										type: "text",
										size: "mini",
										placeholder: "请输入",
									},
									on: {
										input: e => {
											console.log(e)
											this.$set(params.row, "quantity", e)
										},
									},
								})}
							</div>
						)
					},
				},
				{
					prop: "ton",
					label: "重量",
					render: (h, params) => {
						return (
							<div>
								{h("el-input", {
									props: {
										value: params.row.ton,
										type: "text",
										size: "mini",
										placeholder: "请输入",
									},
									on: {
										input: e => {
											console.log(e)
											this.$set(params.row, "ton", e)
										},
									},
								})}
							</div>
						)
					},
				},
				{
					label: "操作",
				},
			],
			dialogVisible: false, // 件号弹框
			pieceNolist: [],
			checkedCities: [], // 件号
			pieceNo: [],
      detailloading: false,
      detailData: [],
      detailcolumns: [
        {
          prop: 'cargoOwnerName',
          label: '货主',
        },
        {
          prop: 'cargoAgentName',
          label: '货代',
        },
        {
          prop: 'cargoName',
          label: '货名',
        },
        {
          prop: 'inOutDate',
          label: '入库时间'
        },
		{
          prop: 'transportEquipmentNo',
          label: '车牌号'
        },
        {
          prop: 'stackPosition',
          label: '垛位号',
        },
        {
          prop: 'pieceNo',
          label: '件号',
        },
        {
          prop: 'quantity',
          label: '件数',
        },
        {
          prop: 'ton',
          label: '重量',
        },
      ],
      showDetailDrawer: false,
      detailForm: {
        inOutDate: '',
        stackPosition: '',
        pieceNo: '',
      },
      // 选中的复选框
      checkedData: [],
		}
	},
	activated() {
		this.getShipVoyage()
	},
	methods: {
		// 获取船名航次
		getShipVoyage() {
			publicapi.getListShipvoyage().then(res => {
				this.shipVoyageData = res.data.data
			})
		},
		// 分页查询
		sizeChange(val) {
			this.queryall.pagesize = val
			this.searchData()
		},
		// 分页查询
		pageChange(val) {
			this.queryall.startpage = val
			this.searchData()
		},
		// 查询主列表
		searchData() {
			this.loading = true
			let params = Object.assign({}, this.queryall, this.searchform)
			api.queryAll(params).then(res => {
				this.loading = false
				if (res.data.code != "0000") {
					return this.$message.error(res.data.msg)
				}
				this.tableData = res.data.data.pages
				this.tableData.forEach(v => {
					v.shipvoyageName = v.shipName + "_" + v.voyage
				})
				this.queryall.startpage = res.data.data.pageNum // 当前页
				this.queryall.pagesize = res.data.data.pageSize // 每页多少
				this.queryall.totalNum = res.data.data.totalNum
			})
		},
		// 点击行
		handlerClickDetails(val) {
			console.log(val)
			this.deatilInfo = val
		},
		// 打开清单页面
		showDetail() {
			if (this.deatilInfo == null) {
				return this.$message.warning("请选中一条数据")
			}

			this.formitem.shipvoyageName = this.deatilInfo.shipvoyageName
			this.formitem.cargoCategoryName = this.deatilInfo.cargoCategoryName
			this.formitem.customerName = this.deatilInfo.customerName

			this.selectInventory()
			this.isShow = true
		},
		// 查询清单
		async selectTYardInOut() {
			let params = {
				shipvoyageId: this.deatilInfo.id,
			}
			await api.selectTYardInOut(params).then(res => {
				this.listTableData = res.data.data

				if (!this.editableTabs.length) {
					this.editableTabs.push({
						title: "1舱口",
						name: "1",
						detailTableData: this.listTableData,
					})
					this.editableTabsValue = "1"
				} else {
					let editLength = this.editableTabs.length - 1
					this.editableTabs[editLength].detailTableData = this.listTableData
				}
			})
		},
		// 新增tab
		addTab(val) {
			var num = 0
			this.editableTabs.forEach(v => {
				if (v.name == val) {
					num++
				}
			})
			if (num > 0) {
				return this.$message.warning("该舱口已存在")
			}
			// this.selectTYardInOut()
			console.log(val)
			this.editableTabs.push({
				title: val + "舱口",
				name: val,
				detailTableData: [],
			})
			this.editableTabsValue = val
			// let editLength = this.editableTabs.length - 1
			// this.editableTabs[editLength].detailTableData = this.listTableData
			console.log(this.editableTabs)
		},
		// 移除tab
		removeTab(targetName) {
			console.log(targetName)
      var tabs = this.editableTabs
			var activeName = this.editableTabsValue
      var idList = []
      this.$confirm('此操作将删除该舱口下的数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
				  tabs.forEach((tab, index) => {
				  	if (tab.name === targetName) {
              console.log(tab)
              idList = tab.detailTableData.map(v => v.id)
            }
          })
          console.log(idList)
          let params = {
            cabinNo: targetName,
            idList: idList
          }
          api.deleteById(params).then(res => {
            if (res.data.code != '0000') {
              return this.$message.error(res.data.msg)
            }
			      if (activeName === targetName) {
			      	tabs.forEach((tab, index) => {
			      		if (tab.name === targetName) {
			      			let nextTab = tabs[index + 1] || tabs[index - 1]
			      			if (nextTab) {
			      				activeName = nextTab.name
			      			}
			      		}
			      	})
			      }
			      this.editableTabsValue = activeName
			      this.editableTabs = tabs.filter(tab => tab.name !== targetName)
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      
		},
		// 删除
		handlerClickDetail(item, index) {
			console.log(item)
			console.log(index)
			return item.splice(index, 1)
		},
		// 点击切换tab
		handleClick(val) {
			console.log(val)
		},
		// 打开件号抽屉
		openPieceNoDrawer(val, index) {
			this.checkedPieceIndex = index
			console.log(val)
			this.getPieceNo(val)
			this.dialogVisible = true
		},
		// 获取件号
		getPieceNo(val) {
			let params = {
				cargoInfoId: val.cargoInfoId,
				stackPosition: val.stackPosition,
			}
			api.selectPieceNo(params).then(res => {
				this.pieceNo = res.data.data
				this.checkedCities = val.pieceNo ? val.pieceNo.split(",") : []
			})
		},
		// 选中件号
		checkChange(val) {
			console.log(val)
		},
		// 确认件号
		submitPieceNo() {
			this.pieceNoList = []
			console.log(this.checkedCities)
			this.checkedCities.forEach(v => {
				this.pieceNo.forEach(j => {
					if (v == j.pieceNo) {
						this.pieceNoList.push({ id: j.id, pieceNo: j.pieceNo })
					}
				})
			})
			var indexp = 0
			this.editableTabs.forEach((v, index) => {
				if (v.name == this.editableTabsValue) {
					indexp = index
				}
			})
			this.editableTabs[indexp].detailTableData[this.checkedPieceIndex].pieceNo = this.checkedCities.join(",")
			this.editableTabs[indexp].detailTableData[this.checkedPieceIndex].listForPieceNo = this.pieceNoList

			this.dialogVisible = false
		},
		// 保存
		saveInventory() {
			var list = []
      this.editableTabs.forEach(v => {
        if (v.name == this.editableTabsValue) {
          v.detailTableData.forEach(i => {
            i.shipvoyageId = this.deatilInfo.id
            i.cabinNo = this.editableTabsValue
          })
          list = v.detailTableData
        }
      })
			
			api.insert(list).then(res => {
				if (res.data.code != "0000") {
					return this.$message.error(res.data.msg)
				}
				this.$message.success("保存成功")
			})
		},
		// 回显
		selectInventory() {
			let params = {
				shipvoyageId: this.deatilInfo.id,
			}
			api.selectTYardLoadingList(params).then(res => {
				if (res.data.code != "0000") {
					return this.$message.error(res.data.msg)
				}
				if (!res.data.data.length) {
					// this.selectTYardInOut()
          this.editableTabs.push({
						title: "1舱口",
						name: "1",
						detailTableData: [],
					})
					this.editableTabsValue = "1"
				} else {
					this.editableTabs = []
					res.data.data.forEach(v => {
						var flag = true
						this.editableTabs.forEach(item => {
							if (v.cabinNo == item.name) {
								item.detailTableData.push(v)
								flag = false
							}
						})
						if (flag) {
							this.editableTabs.push({
								title: v.cabinNo + "舱口",
								name: v.cabinNo + "",
								detailTableData: [v],
							})
						}
					})
				}
			})
		},
		// 抽屉关闭前回调
		handleClose() {
			this.editableTabs = []
			this.isShow = false
		},
    // 显示选择清单抽屉
    showDetailData () {
      this.searchDetailData()
      this.showDetailDrawer = true
    },
    // 查询清单详情
    searchDetailData () {
      let params = {
				shipvoyageId: this.deatilInfo.id,
        inOutDate: this.detailForm.inOutDate,
        stackPosition: this.detailForm.stackPosition,
        pieceNo: this.detailForm.pieceNo
			}
      api.selectTYardInOut(params).then(res => {
				this.detailData = res.data.data
      })
    },
    // 选中复选框
    detailChange (val) {
      this.checkedData = val
    },
    // 保存选中的数据
    saveDetailData () {
      this.editableTabs.forEach(v => {
        if (v.name == this.editableTabsValue) {
          v.detailTableData = v.detailTableData.concat(this.checkedData)
          // v.detailTableData.push(...this.checkedData)
        }
      })
      this.showDetailDrawer = false
    },
	},
}
</script>

<style lang="less" scoped>
@import "../../../assets/searchfrom.less";
/deep/ .el-drawer__header {
	margin-bottom: 0;
	padding: 18px 16px;
	border-bottom: 1px solid gainsboro;
}
/deep/ .el-form-item {
	padding-right: 10px;
}
</style>